package com.alm.token.base;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alm.token.ConStant;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.ui.activity.BlockWalletLoginActivity;
import com.alm.token.ui.activity.MainActivity;
import com.alm.token.ui.activity.PayPwdActivity;
import com.alm.token.ui.activity.TransformActivity;
import com.alm.token.ui.data.BaseDialogBean;
import com.alm.token.ui.data.bean.UpdateData;
import com.alm.token.ui.data.bean.UserWalletData;
import com.alm.token.ui.fragmentDialog.ToSetPayPswDialogFragment;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.BaseView;
import com.alm.token.ui.view.UpdataView;
import com.alm.token.utils.ADBInstallApk;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;
import com.alm.token.utils.LanguageUtils;
import com.alm.token.utils.LogUtil;
import com.alm.token.utils.SpUtil;
import com.alm.token.utils.StatusBarUtil;
import com.gyf.barlibrary.ImmersionBar;
import com.zhy.autolayout.AutoLayoutActivity;

import java.io.File;

import baibeiwallet.utils.DialogUtils;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by lidengzhou on 17/6/12.
 */

public abstract class BaseActivity extends AutoLayoutActivity implements BaseBehavior, ADBInstallApk.adbInstallAPKListener, View.OnClickListener {

    private ImmersionBar mImmersionBar;

    static final String FRAGMENTS_TAG = "android:support:fragments";
    OnBooleanListener onPermissionListener;
    private Unbinder unbinder;
    private BaseBehavior behavior;
    protected MyPreenter preenter;
    protected MyPreenter updataPrenter;

    MyReceiver receiver;

    private void registerBroadcast() {
        // 注册广播接收者
        receiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConStant.EXIT_APP);
        this.registerReceiver(receiver, filter);
    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConStant.EXIT_APP)) {
//                showToast("退出登陆");
                finish();
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        /**
         * 当Activity调用onSaveInstanceState方法的时候，
         * 会保存当前Activity里面的所有Fragment，
         * 保存在了一个Bundle里，key就是FRAGMENTS_TAG。
         * {@link FragmentActivity 的onSaveInstanceState方法}
         * */
        //删除保存的Fragment，重新创建Fragment
        if (savedInstanceState != null) {
            savedInstanceState.putParcelable(FRAGMENTS_TAG, null);
        }
        super.onCreate(savedInstanceState);
//        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            Window window = getWindow();
//            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
//                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//            window.setStatusBarColor(Color.TRANSPARENT);
//            window.setNavigationBarColor(Color.TRANSPARENT);
//        }


        setContentView(getContentViewId());

        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.init();   //所有子类都将继承这些相同的属性
//        //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
//        StatusBarUtil.setRootViewFitsSystemWindows(this,true);
//        //设置状态栏透明
//        StatusBarUtil.setTranslucentStatus(this);
//        //一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
//        //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
//        if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
//            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
//            //这样半透明+白=灰, 状态栏的文字能看得清
//            StatusBarUtil.setStatusBarColor(this,0x55000000);
//        }


        unbinder = ButterKnife.bind(this);
        behavior = new SimpleBehavior(this);
        preenter = initPreenter();
        initVariables();
        initViews();
        loadData();
        registerBroadcast();
    }

    //初始化Preenter
    protected abstract MyPreenter initPreenter();

    //布局文件ID
    protected abstract int getContentViewId();

    //初始化变量
    protected abstract void initVariables();

    //初始化View
    protected abstract void initViews();

    //初始化数据
    protected abstract void loadData();

    @Override
    public void showToast(@StringRes int resId) {
        if (behavior != null) {
            behavior.showToast(resId);
        }
    }

    @Override
    public void showToast(String msg) {
        if (behavior != null) {
            behavior.showToast(msg);
        }
    }

    @Override
    public void showWaitDialog() {
        if (behavior != null) {
            behavior.showWaitDialog();
        }
    }

    @Override
    public void showWaitDialog(@StringRes int resId) {
        if (behavior != null) {
            behavior.showWaitDialog(resId);
        }
    }

    @Override
    public void showWaitDialog(String msg) {
        if (behavior != null) {
            behavior.showWaitDialog(msg);
        }
    }

    @Override
    public MaterialDialog showProgressDialog(Context context, String message, MaterialDialog.SingleButtonCallback callback) {
        if (behavior != null) {
            return behavior.showProgressDialog(context, message, callback);
        }

        return null;
    }

    @Override
    public void showInformationDialog(Context context, String title,
                                      String message, String positiveText, String negativeText, MaterialDialog.SingleButtonCallback callback) {

        if (behavior != null) {
            behavior.showInformationDialog(context, title, message, positiveText, negativeText, callback);
        }

    }

    @Override
    public void hideInformationDialog() {
        if (behavior != null) {
            behavior.hideInformationDialog();
        }
    }

    @Override
    public void hideProgressDialog() {
        if (behavior != null) {
            behavior.hideProgressDialog();
        }
    }

    @Override
    public void hideWaitDialog() {
        if (behavior != null) {
            behavior.hideWaitDialog();
        }
    }

    @Override
    public void showUpdateAlertDialog(Context context, String title, String message, String positiveMsg,
                                      String negativeMsg, MaterialDialog.SingleButtonCallback callback) {
        if (behavior != null) {
            behavior.showUpdateAlertDialog(context, title, message, positiveMsg, negativeMsg, callback);
        }
    }

    @Override
    public void hideUpdateAlertDialog() {
        if (behavior != null) {
            behavior.hideUpdateAlertDialog();
        }
    }

    @Override
    public void startActivity(Class<?> t) {
        if (behavior != null) {
            behavior.startActivity(t);
        }
    }

    @Override
    public void startActivity(Class<?> t, Bundle extra) {
        if (behavior != null) {
            behavior.startActivity(t, extra);
        }
    }

    @Override
    public void startActivityForResult(Class<?> t, int requestCode) {
        if (behavior != null) {
            behavior.startActivityForResult(t, requestCode);
        }
    }

    @Override
    public void startActivityForResult(Class<?> t, int requestCode, Bundle extra) {
        if (behavior != null) {
            behavior.startActivityForResult(t, requestCode, extra);
        }
    }

    @Override
    public void startFragment(Class<?> t) {
        if (behavior != null) {
            behavior.startFragment(t);
        }
    }

    @Override
    public void startFragment(Class<?> t, Bundle extra) {
        if (behavior != null) {
            behavior.startFragment(t, extra);
        }
    }

    @Override
    public void startFragmentForResult(Class<?> t, int requestCode) {
        if (behavior != null) {
            behavior.startFragmentForResult(t, requestCode);
        }
    }

    @Override
    public void startFragmentForResult(Class<?> t, int requestCode, Bundle extra) {
        if (behavior != null) {
            behavior.startFragmentForResult(t, requestCode, extra);
        }
    }

    @Override
    public void handleError(int code, String message) {
        if (behavior != null) {
            behavior.handleError(code, message);
        }
    }

    @Override
    public void hideKeyboard() {
        if (behavior != null) {
            behavior.hideKeyboard();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (preenter != null) {
            preenter.onUnsubscribe();
        }
        if (unbinder != null) {
            unbinder.unbind();
        }

        if (behavior != null) {
            behavior = null;
        }
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
        if (mImmersionBar != null) {
            mImmersionBar.destroy();  //必须调用该方法，防止内存泄漏，不调用该方法，如果界面bar发生改变，在不关闭app的情况下，退出此界面再进入将记忆最后一次bar改变的状态
        }
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (CommonUtil.isShouldHideInput(v, ev)) {
                if (CommonUtil.hideInputMethod(this, v)) {
//                    return true; //隐藏键盘时，其他控件不响应点击事件==》注释则不拦截点击事件
                }
            }
        }
        return super.dispatchTouchEvent(ev);

    }

    @Override
    protected void attachBaseContext(Context newBase) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            super.attachBaseContext(LanguageUtils.wrapContext(newBase));
        } else {
            super.attachBaseContext(LanguageUtils.applyChange(newBase));
        }


    }

    public void onPermissionRequests(String permission, OnBooleanListener onBooleanListener) {
        onPermissionListener = onBooleanListener;
        Log.d("MainActivity", "0");
        if (ContextCompat.checkSelfPermission(this,
                permission)
                != PackageManager.PERMISSION_GRANTED) {
            // Should we show an explanation?
            Log.d("MainActivity", "1");
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_CONTACTS)) {
                //权限已有
                onPermissionListener.PermissionListeneronClick(true);
            } else {
                //没有权限，申请一下
                ActivityCompat.requestPermissions(this,
                        new String[]{permission},
                        1);
            }
        } else {
            onPermissionListener.PermissionListeneronClick(true);
            Log.d("MainActivity", "2" + ContextCompat.checkSelfPermission(this,
                    permission));
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //权限通过
                if (onPermissionListener != null) {
                    onPermissionListener.PermissionListeneronClick(true);
                }
            } else {
                //权限拒绝
                if (onPermissionListener != null) {
                    onPermissionListener.PermissionListeneronClick(false);
                }
            }
            return;
        } else if (requestCode == 222) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                LogUtil.e("Permission: " + permissions[0] + "was " + grantResults[0]);
                m_progressDlg.setTitle(getString(R.string.profile_hint_item21));
                m_progressDlg.setMessage(getString(R.string.profile_hint_item22));
                m_progressDlg.setMax((int) 100);//设置进度条的最大值
                downloadApk();
            } else {
                doNewUpdate(dataBean);//强制更新
//                dialog.show();
            }
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public interface OnBooleanListener {
        public void PermissionListeneronClick(boolean ss);
    }


    /***  弹出提示公告  ***/
    public void showToSetPaypswDialog() {
        boolean bindEmail = true;
        if (EmptyUtils.isNotEmpty(MyApp.getUserData()) && EmptyUtils.isNotEmpty(MyApp.getUserData().getData())) {
            bindEmail = MyApp.getUserData().getData().isBindEmail();
        }
        if (!bindEmail) {
            DialogUtils.toBind(this, getSupportFragmentManager(), true, bindEmail, true, true);
        } else {
            UserWalletData.DataBean.UserMsgBean userMsgBean = new UserWalletData.DataBean.UserMsgBean();
            userMsgBean.setTitle(getString(R.string.common_warmprompt));
            userMsgBean.setContent(getString(R.string.dialog_hint_tosetpaypsw_worm));

            ToSetPayPswDialogFragment dialogFragment = new ToSetPayPswDialogFragment();
            dialogFragment.setDialogBean(new BaseDialogBean("eggroal", userMsgBean));

            dialogFragment.setListener(new ToSetPayPswDialogFragment.ClickListener() {
                @Override
                public void Listener(String name, int potion) {
//                showToast(getString(R.string.paypasw_hint_setpaypsw));
                    Intent intent = new Intent(BaseActivity.this, PayPwdActivity.class);
                    intent.putExtra("PayPwdActivityType", PayPwdActivity.PAYPSW_SET);
                    startActivity(intent);
                    finish();
                }
            });

            dialogFragment.show(getSupportFragmentManager(), "NoticeDialogFragment");
            getFragmentManager().executePendingTransactions();
        }
    }

    public MaterialDialog progressDialog;
    public int mLocalVersionCode;
    public String updateApkUrl, apkname;
    public ProgressDialog m_progressDlg;
    UpdateData.DataBean dataBean;
    /***  需要更新  ***/
    public void showToUpdata() {
        mLocalVersionCode = CommonUtil.getVersionCode(this);

        if (EmptyUtils.isEmpty(updataPrenter)) {
            updataPrenter = new MyPreenter(new UpdataView() {
                @Override
                public void getUpdata(UpdateData updateData) {
                    if (updateData.getStatus() == 0) {//请求成功


                        dataBean = updateData.getData();
                        updateApkUrl = dataBean.getDownload();
                        MyApp.setUpdateApkUrl(updateApkUrl);
                        apkname = dataBean.getApkname() + dataBean.getVersioncode();
                        LogUtil.e("apkname=" + dataBean.getApkname() + " url=" + updateApkUrl + " versioncode=" + dataBean.getVersioncode());
                        if (Integer.parseInt(dataBean.getVersioncode()) > mLocalVersionCode) {
                            MyApp.needUpdaate = true;
                            //下载更新
                            m_progressDlg = new ProgressDialog(BaseActivity.this);
                            m_progressDlg.setCancelable(false);
                            m_progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                            doNewUpdate(dataBean);//强制更新
                        } else {
                            MyApp.needUpdaate = false;
                            SpUtil.putString(BaseActivity.this, ConStant.UPDATEPATH, "");
                        }
                    }
                }

                @Override
                public void getData(Object o) {

                }

                @Override
                public void jumpToLoginAct(int staue) {

                }

                @Override
                public void onError(String error) {

                }

                @Override
                public void ShowProgress() {

                }

                @Override
                public void hideProgress() {

                }
            });
            updataPrenter.getUpdateData1("1");//1 安卓
        }

    }



    private void doNewUpdate(UpdateData.DataBean dataBean) {
        int verCode = CommonUtil.getVersionCode(getApplicationContext());
        String verName = CommonUtil.getVersionName(getApplicationContext());
        String str = getString(R.string.profile_hint_item23, verName, dataBean.getVersion()
                , (!TextUtils.isEmpty(dataBean.getVersiondes()) ? dataBean.getVersiondes() : getString(R.string.profile_hint_item19)));
        CommonUtil.showUpdataDialog(this, str, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog1,
                                int which) {

                if (!isGrantExternalRW(BaseActivity.this)) {
                    return;
                } else {
                    m_progressDlg.setTitle(getString(R.string.profile_hint_item21));
                    m_progressDlg.setMessage(getString(R.string.profile_hint_item22));
                    m_progressDlg.setMax((int) 100);//设置进度条的最大值
                    downloadApk();
                }
            }
        }, new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog1) {

//                dialog.show();

            }
        });
    }

    /**
     * 获取储存权限
     *
     * @param activity
     * @return
     */

    public static boolean isGrantExternalRW(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && activity.checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            activity.requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, 222);

            return false;
        }

        return true;
    }

    protected void downloadApk() {
        if (m_progressDlg != null)
            m_progressDlg.show();
        LogUtil.e("downloadApk.updateApkUrl=" + updateApkUrl);
        ADBInstallApk.getInstance().downloadApk(BaseActivity.this, updateApkUrl, apkname + ".apk", this);
    }

    @Override
    public void onDownloadSuccess(String path) {
        SpUtil.putString(this, ConStant.UPDATEPATH, path);
        down();
    }

    @Override
    public void onDownloading(int progressm) {
        LogUtil.d("99" + "progressm=" + progressm + "");
        if (progressm == 0)
            return;

        m_progressDlg.setProgress(progressm);
    }

    private Handler m_mainHandler;

    /**
     * 告诉HANDER已经下载完成了，可以安装了
     */
    private void down() {
        m_mainHandler = new Handler();
        m_mainHandler.post(new Runnable() {
            public void run() {
                m_progressDlg.cancel();
                update();
            }
        });
    }

    /**
     * 安装程序
     */
    void update() {
//        SPUtils.putBoolean(this, Constant.ISFIRST, false);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(SpUtil.getString(this, ConStant.UPDATEPATH, ""));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri contentUri = FileProvider.getUriForFile(this, getApplication().getPackageName() + ".fileProvider", file);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        startActivity(intent);
        CommonUtil.setDialogNull();
        finish();
//        System.exit(0);
    }
}
